package com.dhcc.core.framework.security.client.oauth2;

import static org.pac4j.core.profile.AttributeLocation.PROFILE_ATTRIBUTE;

import com.dhcc.core.config.properties.SsoProperties;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.scribejava.core.model.OAuth2AccessToken;

import org.pac4j.core.exception.HttpAction;
import org.pac4j.core.profile.ProfileHelper;
import org.pac4j.core.profile.converter.Converters;
import org.pac4j.oauth.config.OAuth20Configuration;
import org.pac4j.oauth.profile.JsonHelper;
import org.pac4j.oauth.profile.definition.OAuth20ProfileDefinition;

public class DthProfileDefinition extends OAuth20ProfileDefinition<DthProfile, OAuth20Configuration> {


    public static final String USER_CODE = "userCode";

    public DthProfileDefinition() {
        primary(USER_CODE, Converters.STRING);
    }

    @Override
    public String getProfileUrl(final OAuth2AccessToken accessToken,
                                final OAuth20Configuration configuration) {
        return SsoProperties.me().getServerUrl() + "/profile?access_token=" + accessToken.getAccessToken();
    }

    @Override
    public DthProfile extractUserProfile(final String body) throws HttpAction {
        final DthProfile profile = new DthProfile();
        final JsonNode json = JsonHelper.getFirstNode(body);
        if (json != null) {
            profile.setId(ProfileHelper.sanitizeIdentifier(profile, JsonHelper.getElement(json, USER_CODE)));
            for (final String attribute : getPrimaryAttributes()) {
                convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute,
                    JsonHelper.getElement(json, attribute));
            }
        } else {
            raiseProfileExtractionJsonError(body);
        }
        return profile;
    }

}
